package com.soulkun.smarthome.logic.interceptor

import com.soulkun.smarthome.logic.Constant
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import soulkun.library.helper.sharedpreferences.SharedPreferencesHelper
import soulkun.library.utils.getAppContext
import soulkun.library.utils.logE

/**
 * Token拦截器，负责添加Token
 */
class TokenInterceptor : Interceptor {

    private val sharedPreferencesHelper = SharedPreferencesHelper(getAppContext().packageName)

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request().setToken()
        return chain.proceed(request).getToken()
    }

    private fun Request.setToken(): Request {
        val ignoreToken = this.header("Ignore-Token") //如果没有，默认为true
        val needRefresh = this.header("Need-Refresh") //如果没有，默认为false
        return if (ignoreToken == "false") { //需要Token
            if (needRefresh == "true") { //必须携带Refresh
                this.newBuilder()
                    .addHeader(
                        "Authorization",
                        sharedPreferencesHelper.getString(Constant.SHARED_PREFERENCE_ACCESS_TOKEN)
                    )
                    .addHeader(
                        "Refresh",
                        sharedPreferencesHelper.getString(Constant.SHARED_PREFERENCE_REFRESH_TOKEN)
                    )
                    .build()
            }else{ //按照访问时间判断是否需要
                if (System.currentTimeMillis() < sharedPreferencesHelper.getLong(Constant.SHARED_PREFERENCE_ACCESS_TIME) - 1000 * 60) {
                    this.newBuilder()
                        .addHeader(
                            "Authorization",
                            sharedPreferencesHelper.getString(Constant.SHARED_PREFERENCE_ACCESS_TOKEN)
                        )
                        .build()
                } else {
                    this.newBuilder()
                        .addHeader(
                            "Authorization",
                            sharedPreferencesHelper.getString(Constant.SHARED_PREFERENCE_ACCESS_TOKEN)
                        )
                        .addHeader(
                            "Refresh",
                            sharedPreferencesHelper.getString(Constant.SHARED_PREFERENCE_REFRESH_TOKEN)
                        )
                        .build()
                }
            }
        } else { //不需要Token
            this
        }
    }

    private fun Response.getToken(): Response {
        val accessToken = header("Authorization")
        val accessTime = header("Access-Time")
        if (accessToken != null && accessTime != null) {
            sharedPreferencesHelper.putString(Constant.SHARED_PREFERENCE_ACCESS_TOKEN, accessToken)
            sharedPreferencesHelper.putLong(Constant.SHARED_PREFERENCE_ACCESS_TIME, accessTime.toLongOrNull() ?: 0L)
        }
        return this
    }

}